import { ref } from 'vue'
import { supabase } from '../config/supabase'

export const useAuth = () => {
  const user = ref(null)
  const loading = ref(false)
  const error = ref(null)

  // 检查当前会话
  const checkUser = async () => {
    try {
      const { data: { user: currentUser } } = await supabase.auth.getUser()
      user.value = currentUser
    } catch (err) {
      error.value = err.message
    }
  }

  // 登录方法
  const signIn = async (email, password) => {
    try {
      loading.value = true
      const { data, error: signInError } = await supabase.auth.signInWithPassword({
        email,
        password,
      })
      if (signInError) throw signInError
      user.value = data.user
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  // 注册方法
  const signUp = async (email, password, nickname) => {
    try {
      loading.value = true
      // 先创建 profile 记录
      const { data: authData, error: signUpError } = await supabase.auth.signUp({
        email,
        password,
        options: {
          data: {
            nickname: nickname
          }
        }
      })
      
      if (signUpError) throw signUpError

      if (authData.user) {
        const { error: profileError } = await supabase
          .from('profiles')
          .insert([
            {
              id: authData.user.id,
              nickname,
              avatar_url: `https://api.dicebear.com/7.x/initials/svg?seed=${nickname}`,
              updated_at: new Date().toISOString(),
            }
          ])
          .select()
        
        if (profileError) throw profileError
        
        // 注册成功后提示用户验证邮箱
        return { message: '注册成功，请检查邮箱并验证后登录' }
      }
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const signOut = async () => {
    try {
      loading.value = true
      await supabase.auth.signOut()
      user.value = null
    } catch (err) {
      error.value = err.message
    } finally {
      loading.value = false
    }
  }

  return {
    user,
    loading,
    error,
    signIn,
    signUp,
    signOut,
    checkUser
  }
}
